<template>
  <page-layout>
    <a-row :gutter="[10, 10]">
      <!-- 中心区域 -->
      <a-col :span="24">
        <a-card>
          <!-- 列表 -->
          <go2-table ref="tableRef" rowKey="id" :indentSize="10" :fetch="fetch" :columns="columns" :toolbar="toolbar"
            :operate="operate" :param="state.param" :pagination="pagination" :row-selection="rowSelection"
            :customRow="customRow">
            <!-- 继承至 a-table 的默认插槽 -->
          </go2-table>

        </a-card>
      </a-col>
    </a-row>
    <add
      v-if="state.visibleModal.includes('add')"
      :visible="state.visibleModal.includes('add')"
      @close="closeModal"
    ></add>
    <edit
      v-if="state.visibleModal.includes('edit')"
      :visible="state.visibleModal.includes('edit')"
      @close="closeModal"
      :record="state.recordEdit"
    ></edit>
    <info
      v-if="state.visibleModal.includes('info')"
      :visible="state.visibleModal.includes('info')"
      @close="closeModal"
      :record="state.recordInfo"
    ></info>
  </page-layout>
</template>

<script>




import { useI18n } from "vue-i18n";
import add from "./modal/add.vue";
import edit from "./modal/edit.vue";
import info from "./modal/info.vue";
import { message, Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { list, remove } from "@/app/api/{{.TableName}}";
import { reactive, createVNode, ref, toRaw, computed } from 'vue';
import { useRoute, useRouter } from "vue-router";

const removeKey = "remove";
export default {
  components: {
    info,
    add,
    edit,
  },
  setup(props, { emit }) {
    const router = useRouter();
    const { t } = useI18n();
    const tableRef = ref();

    const switchFormat = {
      yes: 1,
      no: 0,
      event: function (value, record) {
        return value;
      },
    };

    /// 外置参数 - 当参数改变时, 重新触发 fetch 函数
    const state = reactive({
      selectedRowKeys: [],
      selectedRows: [],
      param: {}, 
      visibleModal: [], 
      recordSelected: {},
      recordEdit: {},
      recordInfo: {},
    });

    /// 删除配置
    const removeMethod = (record) => {
      removeIds([record.id]);
    };


    const removeIds = (Ids) => {
      Modal.confirm({
        title: t("confirm") + t("delete") + "?",
        icon: createVNode(ExclamationCircleOutlined),
        okText: t("ok"),
        cancelText: t("cancel"),
        onOk() {
          message.loading({ content: t("loading"), key: removeKey });
          remove({ ids: Ids }).then((response) => {
            if (response.code == 0) {
              message
                .success({
                  content: t("Delete succeeded!"),
                  key: removeKey,
                  duration: 1,
                })
                .then(() => {
                  tableRef.value.reload();
                });
            } else {
              message.error({
                content: response.msg,
                key: removeKey,
                duration: 1,
              });
            }
          });
        },
      });
    };

    /// 列配置
    const columns = [
     {{range .Fields }} 
     {{if .List}}{{if eq .Type "time.Time"}}{title:"{{.Comment}}", dataIndex: "{{.Json}}", key: "{{.Json}}", format: { type: "date", value: "YYYY-MM-DD HH:mm:ss" } },{{else}}{ title:"{{.Comment}}",dataIndex: "{{.Json}}", key: "{{.Json}}" },{{end}}{{end}}
    {{ end }} 
    ];
    /// 数据来源
    const fetch = async (param) => {
      var response = await list(param);

      if (response.code != 0) {
        message.error({ content: response.msg, duration: 1 });
      }
      return { data: response.data };
    };

    /// 工具栏
    const toolbar = [
      { label: 'add', code: '/{{.TableName}}/add', event: function () { state.visibleModal = ["add"]; } },
      {
        label: "info",
        code: "/{{.TableName}}/list",
        event: function (record) {
          if (state.selectedRows.length > 0) { state.visibleModal = ["info"], state.recordInfo = state.selectedRows[0]; }
          else {
            message.error({ content: t('please chose'), key: state.selectedRowKeys, duration: 1 })
          }
        },
      },
      {
        label: "edit",
        code: "/{{.TableName}}/edit",
        event: function () {
          if (state.selectedRows.length > 0) {
            state.visibleModal = ["edit"], state.recordEdit = state.selectedRows[0];
          }
          else {
            message.error({ content: t('please chose'), key: state.selectedRowKeys, duration: 1 })
          }
        },
      }, 
      {
        label: "remove",
        code: "/{{.TableName}}/remove",
        event: function (record) {
          if (state.selectedRows.length > 0) {
            removeMethod(state.selectedRows[0]);
          }
          else {
            message.error({ content: t('please chose'), key: state.selectedRowKeys, duration: 1 })
          }
        },
      },
    ];

    /// 行操作
    const operate = [];

    /// 分页参数
    const pagination = reactive({
      pageSize: 20,
      page: 1,
    });

 

    const rowSelection = computed(() => {
      const _rowSelection = {
        type: "radio",
        selectedRowKeys: state.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          state.selectedRowKeys = selectedRowKeys;
          state.selectedRows = selectedRows;
        },
      };

      return _rowSelection;
    });

    //行点击事件
    const selectRow = (record) => {
      state.selectedRowKeys = [record.id];
      state.selectedRows = [record];
    };
    const customRow = (record) => {
      return {
        onClick: () => {
          selectRow(record);
        },
      };
    };

     
    const closeModal = function (e) {
      state.visibleModal = [];
      if (e) {
        tableRef.value.reload()
        state.selectedRowKeys = [];
        state.selectedRows = [];
      }
    }

    return {
      t,
      state,
      fetch, 
      toolbar,
      columns,
      operate,
      pagination, 
      rowSelection,
      selectRow,
      customRow,
      closeModal, 
      tableRef,
    };
  },
};
</script>